package com.mzba.easy.weibo.ui;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.MenuItem;
import com.mzba.easy.weibo.BasicActivity;
import com.mzba.easy.weibo.R;
import com.mzba.easy.weibo.db.UserEntry;
import com.mzba.easy.weibo.util.ServiceUtils;
import com.mzba.easy.weibo.util.UICore;
import com.mzba.easy.weibo.util.WeiboManager;
import com.viewpagerindicator.PageIndicator;
import com.viewpagerindicator.TabPageIndicator;
import com.viewpagerindicator.TitleProvider;
/**
 * 
 * @author 06peng
 *
 */
public class UserinfoActivity extends BasicActivity implements Callback {
	
	private Handler handler;
	public final int init_userinfo = 1;
	private final int destroy_friend = 2;
	private final int add_friend = 3;
	private final int destroy_friend_error = 4;
	private final int add_friend_error = 5;
	public static final int LOADFINISH = 0x00000105;
	private String userid;
	private UserEntry entry;
	private Bitmap bitmap;
	private WeiboManager weiboManager;
	
	private ViewPager mPager;
	private PageIndicator mIndicator;
	private TabsAdapter mAdapter;
	
	private ImageView avatarView;
	private ImageView sexView;
	private TextView usernameView;
	private TextView detailView;
	private TextView friendView;
	
	private ActionBar actionBar;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.userinfo);
        handler = new Handler(this);
        weiboManager = new WeiboManager(this);
		avatarView = (ImageView) findViewById(R.id.userinfo_avatar);
		sexView = (ImageView) findViewById(R.id.userinfo_sex);
		usernameView = (TextView) findViewById(R.id.userinfo_name);
		detailView = (TextView) findViewById(R.id.userinfo_detail);
		friendView = (TextView) findViewById(R.id.userinfo_friend_button);
		userid = getIntent().getStringExtra("userid");
		
		actionBar = getSupportActionBar();
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(true);
		
		mAdapter = new TabsAdapter(getSupportFragmentManager(), this);
		Bundle bundle = new Bundle();
		bundle.putString("userid", userid);
		mAdapter.addFragment("TA的微博", UserinfoTimeLineFragment.class, bundle);
		mAdapter.addFragment("TA的关注", UserinfoFriendsFragment.class, bundle);
		mAdapter.addFragment("TA的粉丝", UserinfoFollowersFragment.class, bundle);
		mPager = (ViewPager) findViewById(R.id.pager);
		mPager.setAdapter(mAdapter);

		mIndicator = (TabPageIndicator) findViewById(R.id.indicator);
		mIndicator.setViewPager(mPager);
		
        UICore.eventTask(this, this, init_userinfo, "", null);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	if (item.getItemId() == android.R.id.home) {
    		finish();
    	}
    	return false;
    }
    
	private void updateUI() {
    	if (entry == null) {
    		return;
    	}
    	findViewById(R.id.userinfo_layout).setVisibility(View.VISIBLE);
    	if (bitmap != null) {
    		avatarView.setImageBitmap(bitmap);
    	}
    	actionBar.setTitle(entry.getScreen_name() + "的资料");
    	if (entry.getGender().equals("m")) {
			sexView.setImageDrawable(getResources().getDrawable(R.drawable.user_info_male));
		} else if (entry.getGender().equals("f")) {
			sexView.setImageDrawable(getResources().getDrawable(R.drawable.user_info_female));
		}
    	usernameView.setText(entry.getScreen_name());
    	detailView.setText(entry.getDescription());
    	if (entry.isFollowing()) {
    		friendView.setText("取消关注");
    	} else {
    		friendView.setText("关注TA");
    	}
    	friendView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (entry.isFollowing()) {
					UICore.eventTask(UserinfoActivity.this, UserinfoActivity.this, destroy_friend, "", null);
				} else {
					UICore.eventTask(UserinfoActivity.this, UserinfoActivity.this, add_friend, "", null);
				}
			}
		});
    }
    
    @Override
    public void execute(int mes, Object obj) {
    	switch (mes) {
		case init_userinfo:
			entry = weiboManager.getUserByUserid(userid);
			bitmap = ServiceUtils.downloadImage(entry.getProfile_image_url());
			handler.sendEmptyMessage(init_userinfo);
			break;
		case add_friend:
			UserEntry userEntry = weiboManager.friendCreate(userid, entry.getScreen_name());
			if (userEntry != null) {
				handler.sendEmptyMessage(add_friend);
			} else {
				handler.sendEmptyMessage(add_friend_error);
			}
			break;
		case destroy_friend:
			UserEntry userEntry2 = weiboManager.friendDestroy(userid, entry.getScreen_name());
			if (userEntry2 != null) {
				handler.sendEmptyMessage(destroy_friend);
			} else {
				handler.sendEmptyMessage(destroy_friend_error);
			}
			break;
		default:
			break;
		}
    	
    }

    public void showOrHideProgress(boolean showOrHide) {
    	setSupportProgressBarIndeterminateVisibility(showOrHide);
    }
    
	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case init_userinfo:
			updateUI();
			break;
		case add_friend:
			friendView.setText("取消关注");
			entry.setFollowing(true);
			break;
		case add_friend_error:
			onToast("添加关注失败！");
			break;
		case destroy_friend:
			friendView.setText("关注TA");
			entry.setFollowing(false);
			break;
		case destroy_friend_error:
			onToast("取消关注失败！");
			break;
		case LOADFINISH:
			showOrHideProgress(false);
			break;
		default:
			break;
		}
		return false;
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			if (bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
				bitmap = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static class TabsAdapter extends FragmentPagerAdapter implements TitleProvider  {

    	private Context mContext;
		private final ArrayList<FragmentInfo> fragments = new ArrayList<FragmentInfo>();
		
		protected static final class FragmentInfo {
			private final String tag;
            private final Class<?> clss;
            private final Bundle args;

            protected  FragmentInfo(String _tag, Class<?> _class, Bundle _args) {
                tag = _tag;
                clss = _class;
                args = _args;
            }
        }
    	
		public TabsAdapter(FragmentManager fm, Context context) {
			super(fm);
			this.mContext = context;
		}
		
		public void addFragment(String tag, Class<?> clss, Bundle args) {
			FragmentInfo fragmentInfo = new FragmentInfo(tag, clss, args);
			fragments.add(fragmentInfo);
		}

		@Override
		public Fragment getItem(int arg0) {
			FragmentInfo fragmentInfo = fragments.get(arg0);
			Fragment fragment = Fragment.instantiate(mContext, fragmentInfo.clss.getName(), fragmentInfo.args);
			return fragment;
		}

		@Override
		public int getCount() {
			return fragments.size();
		}

		@Override
		public String getTitle(int position) {
			return fragments.get(position).tag;
		}
    }
	
	public void loading() {
		try {
			if (this.isFinishing()) {
				return;
			}
			showOrHideProgress(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void loadFinish() {
		handler.sendEmptyMessage(LOADFINISH);
	}
	
}